package com.tools.common.thread;

import com.tools.common.container.OwnRows;
import com.tools.common.container.RowKit;
import com.tools.common.object.C;
import com.tools.common.object.Note;
import com.tools.common.object.ObjKit;
import com.tools.common.object.string.StrKit;

import java.util.Collection;

/**
 * 默认实现的线程子类对象
 * 加入了自定义参数的使用
 * */
@Note("默认实现的线程子类对象" +
        "加入了自定义参数的使用")
public class OwnThread extends Thread {

    @Note("自定义参数的存储容器")
    private Object[] parameters;

    /* *******************************************************************************************
     *
     *           构造器
     *
     * *******************************************************************************************
     * */

    public OwnThread() {}

    public OwnThread(Object param) {
        if(param == null) return;
        this.parameters = new Object[] {param};
    }

    public OwnThread(Object... params) {
        if(params == null || params.length == 0) return;
        this.parameters = params;
    }

    public OwnThread(Collection<?> params) {
        if(params == null || params.isEmpty()) return;
        this.parameters = params.toArray();
    }

    public OwnThread(OwnRows<?> params) {
        if(params == null || params.isEmpty()) return;
        this.parameters = params.toArray();
    }

    public OwnThread(Iterable<?> params) {
        if(params == null) return;
        int size = RowKit.getIterableSize(params);
        if(size == 0) return;
        this.parameters = new Object[size];
        int index = 0;
        for (Object param : params) {
            if(index == size) return;
            this.parameters[index] = param;
            index++;
        }
    }


    /* *******************************************************************************************
     *
     *           其他方法
     *
     * *******************************************************************************************
     * */

    public void task() throws Exception {

    }

    @Override
    public void run() {

    }

    public final Object getParam(int index) {
        if(parameters == null || parameters.length == 0) return null;
        if(index < 0 || index >= parameters.length) return null;
        return parameters[index];
    }

    public final  <T>T getParam(int index, Class<T> parameterType) {
        return (T) getParam(index);
    }

    public final <T>T getParam(int index, C<T> parameterType) {
        Object parameter = getParam(index);
        return (T) ObjKit.toRealValue(parameter, parameterType);
    }

    public final int getParamSize() {
        return (parameters == null) ? 0 : parameters.length;
    }

    @Override
    public String toString() {
        return StrKit.toString(parameters);
    }
}
